package com.xuecheng.content.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.basic.api.BasicClient;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.TeachplanVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioTemplate;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.CoursePub;
import com.xuecheng.content.mapper.CoursePubMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.content.service.CoursePubService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.minio.messages.DeleteRequest;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-03
 */
@Service
public class CoursePubServiceImpl extends ServiceImpl<CoursePubMapper, CoursePub> implements CoursePubService {

    @Autowired
    private TeachplanService teachplanService;

    @Autowired
    private CourseBaseService courseBaseService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private BasicClient basicClient;
    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private AsyncCoursePubService asyncCoursePubService;
    // 课程预览
    @Override
    public Map preview(Long courseBaseId) {
        // 1.查询课程计划
        ResponseResult<TeachplanVo> responseResult = teachplanService.treeNodes(courseBaseId);
        TeachplanVo teachplanVo = responseResult.getData();
        // 2.准备课程发布对象
        // 2-1 课程基本信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        CoursePub coursePub = BeanHelper.copyProperties(courseBase, CoursePub.class);
        coursePub.setCourseId(courseBaseId);// 单独设置课程id
        // 2-2 课程分类名称（mt：大分类、st：小分类）
        String mtName = getCategoryId(coursePub.getMt());
        coursePub.setMtName(mtName);
        String stName = getCategoryId(coursePub.getSt());
        coursePub.setStName(stName);
        // 2-3 课程计划
        coursePub.setTeachplan(JSON.toJSONString(teachplanVo));
        // 2-4 课程价格
        coursePub.setPrice(courseBase.getPrice().longValue());
        // 2-5 发布时间
        coursePub.setCreateDate(new Date());
        // 3.将数据填充到模型
        Map model = new HashMap();
        model.put("coursePub", coursePub);
        model.put("teachplanNode", teachplanVo);

        // 4.返回模型
        return model;
    }

    // 课程发布
    @Transactional
    @Override
    public ResponseResult publish(Long courseBaseId) throws Exception {
        // 1.查询课程信息
        CourseBase courseBase = courseBaseService.getById(courseBaseId);
        // 2.校验课程状态
        if (!StrUtil.equals(courseBase.getAuditStatus(), CourseConstants.AUDIT_PASTED_STATUS)) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        // 3.获取课程发布对象
        Map map = this.preview(courseBaseId);
        CoursePub coursePub = (CoursePub) map.get("coursePub");
        // 4.发布对象保存
        this.saveOrUpdate(coursePub);
        // 5.更新课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_PUBLISHED_STATUS);
        courseBaseService.updateById(courseBase);
        // 异步多线程调用
        asyncCoursePubService.publish(map,courseBaseId);
        // 发送mq消息  课程id = 课程发布id
        rabbitTemplate.convertAndSend("content-exchange","course.pub",coursePub.getId());
        // 返回ok
        return ResponseResult.okResult();
    }


    //课程下架
    @Override
    public ResponseResult offline(Long courseId) throws IOException {

        //修改课程状态
        // 1.查询课程信息
        CourseBase courseBase = courseBaseService.getById(courseId);
        //2.检测课程状态
        String auditStatus = courseBase.getAuditStatus();
        //只有已发布的才可以下架
        //只有已发布的才可以下架
        if (!auditStatus.equals(CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        // 3.更新课程状态
        courseBase.setAuditStatus(CourseConstants.AUDIT_COMMIT_STATUS);
        courseBaseService.updateById(courseBase);

        //删除minio静态页
        minioTemplate.removeObject("pages/"+courseId+".html");
        //删除mysql中的课程发布表数据
        boolean isSuccess = this.removeById(courseId);
        if (isSuccess==false) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        // 发送mq消息  课程id = 课程下架id
        rabbitTemplate.convertAndSend("offline-exchange", "content-exchange",courseBase.getId().toString());
        //返回
        return ResponseResult.okResult();
    }


    // feign查询方法抽取
    private String getCategoryId(String categoryId) {
        ResponseResult<CategoryVo> categoryVoResponseResult = basicClient.findById(categoryId);
        if (categoryVoResponseResult.getCode()!=0) {
            throw new BusinessException(ErrorCode.NOTFOUND);
        }
        CategoryVo categoryVo = categoryVoResponseResult.getData();
        String name = categoryVo.getName();
        return name;
    }
}
